from flask import Blueprint,jsonify,request
from conf.comm import sqlalchemy_context
from database import *
import json
# 实例化
bp_course = Blueprint('course',__name__)


# 无限极分类构造
def xtree(data):
    tree = {}
    list = []
    if data:
        # 解析成字典
        for i in data:
            tree[i['id']] = i

        for i in data:
            # 判断是否有父类
            if j['parent'] == 0:
                lsit.append(j)
            else:
                # 有父类
                # 查看父类是否有子类,如果有append,如果没有初始化
                if 'son' not in tree [j['parent']]:
                    tree  [j['parent']]['son']=[]
                # 把子类加到特定的父类下
                tree[j['parent']]['son'].append(j)
        return list
    
# 添加分类
@db_course.route('/cateM'，methods=['POST','GET'])
@sqlalchemy_context()
def cateM():
    if request.method == "POST":
        try:
            # 获取用户信息
            if data:
                data = request.data
            else:
                data = request.form
            # 构造对象
            cate = Cate(name=data['name'],parent=data['parent'],level=data['level'],params=data['params'])
            # 添加
            db.session.add(cate)
            # 提交
            db.session.commit()
            # 返回结果  
            return jsonify({'code':200})

        except:
            return jsonify({'code':10010})
    else:
        # 获取所有分类
        list = []
        cate = Cate.query.all()
        if cates:
            for i in cates:
                dict = {'id':i.id,'name'i.name,'parent'i.parent,'params'i.params,'lecel'i.level}
                list.append(dict)
        list = xtree(list)
        return jsonify({"code":200,"list":list1})
  